package geom;

import geom.Line;
import geom.Vector;

import java.util.ArrayList;
import java.util.Iterator;


import processing.core.PApplet;

public class VectorFieldFollowers extends PApplet{
	ArrayList<TangentLine> lines;
	TangentLine line;
	static public void main(String args[]) {
		PApplet.main(new String[] { 

			"--present",
			"geom.VectorFieldFollowers" 
		});
	}
	public void setup(){
		size(1440, 900);
		frameRate(266);
		smooth();
		lines = new ArrayList<TangentLine>();
		line = null;
		field = new AngleField();
		background(0);
		initFollowers(500);
	}
	ArrayList<FieldFollower> followers;
	
	public void initFollowers(int num){
		followers = new ArrayList<FieldFollower>(num);
		for(int i = 0; i < num; i++){
			followers.add(new FieldFollower(new Vector(random(1440), random(900)), field));
		}
		
	}
	public void draw(){
		
		Iterator<TangentLine> i = lines.iterator();
		noFill();
		while(i.hasNext()){
			TangentLine next = i.next();
			strokeWeight(1);
			stroke(150, 90, 100, 120);
			next.draw(this);
			//stroke(30, 120, 200);
			//next.drawHeadings(this);
		}
		if(line != null){
			stroke(90, 150, 100);
			line.draw(this);
			//stroke(30, 160, 240);
			//line.drawHeadings(this);
		}
		if(followers == null) return;
		Iterator<FieldFollower> iff = followers.iterator();
		while(iff.hasNext()){
			stroke(90, 150, 255, 90);
			iff.next().draw(this);
		}
		for(int n = 0; n < followers.size(); n++){
			FieldFollower next = followers.get(n);
			while(next.pos.x <= -50 || next.pos.x > 1490 || next.pos.y <= -50 || next.pos.y > 950){
				followers.remove(n);
				if(n >= followers.size()) break;
				next = followers.get(n);
			}
		}
		//field.draw(this, 800, 800, 8);
	}
	public void mouseClicked(){
		if(followers == null) return;
		followers.add(new FieldFollower(new Vector(mouseX, mouseY), field));
	}
	public void keyPressed(){
		if(this.keyCode == this.ENTER)
			initFollowers(0);
		if(this.key == 'f'){
			stroke(220, 40, 10, 50);
			field.draw(this, 800, 800, 8);
		}
		if(this.key == 'a'){
			followers.add(new FieldFollower(new Vector(mouseX, mouseY), field));
		}
		if(this.key == 'c'){
			followers = new ArrayList<FieldFollower>();
		}
		
	}
	AngleField field = null; 
	
	public void mousePressed(){
		line = new TangentLine();
	}
	
	public void mouseReleased(){
		field.add(line.getLines());
		line = null;
	}
	
	public ArrayList<Line> getAll(){
		ArrayList<Line> all = new ArrayList<Line>();
		Iterator<TangentLine> il = lines.iterator();
		while(il.hasNext()) all.addAll(il.next().getLines());
		return all;
	}
	
	public void mouseDragged(){
		line.add(new Vector(mouseX, mouseY));
	}
	

}
